package _01_动态数组;

import java.util.Arrays;

public class _167_两数之和II输入有序数组 {

    public static void main(String[] args) {
        int[] ins = {5, 25, 75};
        System.out.println(Arrays.toString(twoSum(ins, 100)));
    }

    // 利用二分查找
    public static int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        int end = numbers.length - 1;
        for (int i = 0; i < numbers.length; i++) {
            result[0] = i + 1;
            int remain = target - numbers[i];
            if ((result[1] = binarySearch(numbers, i + 1, end, remain)) != -1) {
                result[1] += 1;
                break;
            }
        }
        return result;
    }

    public static int binarySearch(int[] nums, int begin, int end, int target) {
        while (begin <= end) {
            int mid = begin + end >> 1;
            if (nums[mid] > target) {
                end = mid - 1;
            } else if (nums[mid] < target) {
                begin = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

}
